package com.example.music_player_app.ui.playListDetail;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.example.music_player_app.Bean.SongDetail;
import com.example.music_player_app.MainActivity;
import com.example.music_player_app.R;
import com.example.music_player_app.api.service.playList.SongUrlService;
import com.example.music_player_app.ui.playSong.PlaySong;
import com.example.music_player_app.utils.ApiServer;
import com.example.music_player_app.utils.CookieServer;
import com.example.music_player_app.utils.DBHelper;

import java.util.List;

import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class MySongAdapter extends BaseAdapter implements View.OnClickListener{
    private List<SongDetail> list;
    private Context context;
    private DBHelper dbHelper;
    private SQLiteDatabase db;
    private Cursor cursor;

    public MySongAdapter(List<SongDetail> list, Context context) {
        this.list = list;
        this.context = context;
    }
    @Override
    public int getCount() {
        return list.size();
    }

    @Override
    public Object getItem(int position) {
        return list.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        if(convertView == null) {
            convertView = LayoutInflater.from(context).inflate(R.layout.song_list_item, parent, false);
        }

        TextView textView = convertView.findViewById(R.id.song_name);
        textView.setText(list.get(position).getName());

        TextView textView2 = convertView.findViewById(R.id.singer);
        textView2.setText(list.get(position).getSinger());

        Button button = convertView.findViewById(R.id.play_song); // 播放按钮
        button.setTag(R.id.btn, position);
        button.setOnClickListener(this);

        Button button1 = convertView.findViewById(R.id.add_song); // 收藏按钮
        button1.setTag(R.id.btn, position);
        button1.setOnClickListener(this);

        dbHelper = new DBHelper(context, "musicPlayerDB.db", null, 1);
        db = dbHelper.getWritableDatabase();

        return convertView;
    }

    @SuppressLint("NonConstantResourceId")
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.play_song:
                int b = (int) v.getTag(R.id.btn);
                getSongUrl(b, false);
                Log.i("click", "onClick: button" + b);
                break;
            case R.id.add_song:
                int bb = (int) v.getTag(R.id.btn);
                getSongUrl(bb, true);
                Log.i("click", "onClick: 收藏");
                break;
        }
    }

    // 点击播放按钮并跳转到播放页面
    // isAdd表示是否收藏按钮
    private void getSongUrl(int b, boolean isAdd) {
        new Thread(){
            @Override
            public void run() {
                ApiServer http = new ApiServer();
                SongUrlService songUrlService = http.getRetrofit().create(SongUrlService.class);
                Call<ResponseBody> call = songUrlService.get(CookieServer.getCookie(), list.get(b).getId());
                call.enqueue(new Callback<ResponseBody>() {
                    @Override
                    public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                        try {
                            JSONObject jsonObject = (JSONObject) JSONObject.parse(response.body().string());
                            JSONArray jsonArray = jsonObject.getJSONArray("data");
                            String url = jsonArray.getJSONObject(0).getString("url");
                            list.get(b).setPlayUrl(url); // 设置播放url
                            String sql = "";

                            if(isAdd) { // 收藏
                                SongDetail songDetail = list.get(b);
                                sql = "select * from myMusic where id=" + songDetail.getId();
                                cursor = db.rawQuery(sql,null);
                                if(cursor.getCount() > 0) {
                                    Toast.makeText(context,"该歌曲以收藏，请勿重复收藏",Toast.LENGTH_SHORT).show();
                                }else {
                                    sql = "insert into myMusic values("
                                            + songDetail.getId() + ","
                                            + "'" + songDetail.getName() + "'" + ","
                                            + "'" + songDetail.getSinger() + "'" + ","
                                            + "'" + songDetail.getSongImgUrl() + "'" + ","
                                            + "'" + songDetail.getPlayUrl() + "'" + ")";
                                    db.execSQL(sql);
                                    Toast.makeText(context,"收藏成功",Toast.LENGTH_SHORT).show();
                                }
                            }else { // 播放
                                //创建意图对象
                                Intent intent = new Intent(context, PlaySong.class);
                                Bundle bundle = new Bundle();
                                bundle.putSerializable("song_detail",list.get(b));
                                bundle.putBoolean("isClickPlay", true);
                                intent.putExtras(bundle);
                                context.startActivity(intent);
                            }

                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                    @Override
                    public void onFailure(Call<ResponseBody> call, Throwable t) {
                        Log.i("fail", "onFailure: " + t);
                    }
                });
            }
        }.start();
    }
}
